package com.ssjhs.installservice;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.List;

/**
 * 1.传输APK文件到本地
 * 2.更新APP
 * 3.IP ID SIDE等信息配置
 * 4.监视APP运行,并可重启APP
 */

public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private IAppManager appManager;

    boolean mBound = false; // 一开始，并没有和Service绑定.这个参数是用来判断绑定状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_bind).setOnClickListener(this);
        findViewById(R.id.btn_unbind).setOnClickListener(this);
        findViewById(R.id.btn_start).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);
        findViewById(R.id.btn_install).setOnClickListener(this);

//        button_bind_service.callOnClick();

//        finish();
//        button_install.callOnClick();

        startService();
        finish();
    }

    // 匿名内部类：服务连接对象
    private ServiceConnection connection = new ServiceConnection() {

        // 当服务异常终止时会调用。注意，解除绑定服务时不会调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false; // 服务异常终止时，状态为未绑定
        }

        // 和服务绑定成功后，服务会回调该方法。在这个方法里调用的业务对象中的内容
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected");
            appManager = IAppManager.Stub.asInterface(service); // 得到person对象
            Log.d(TAG, "appManager 对象的内存地址是" + appManager); // 打印出person对象的内存地址
            mBound = true; //true说明是绑定状态
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_start:
//                Intent bindIntent = new Intent(this, ManagerService.class);

//                Intent intent = new Intent();
//                intent.setAction("com.boomstack.aidl");
//                intent.setPackage("com.boomstack.testaidlserver");
//                bindService(intent, serviceConnection, BIND_AUTO_CREATE);

                startService();
                break;
            case R.id.btn_stop:
                stopService();
                break;
            case R.id.btn_bind:
                bindService();
                break;
            case R.id.btn_unbind:
                unbindService();
                break;
            case R.id.btn_install:
                ApkManage.autoInstallApk("/sdcard/app-debug.apk", "com.ssjhs.camerarec");
                break;
            default:
                break;
        }
    }

    private void startService() {
        if (!isServiceRunning(this, getPackageName())) {
            String packageName = getPackageName();
            Intent intent = new Intent(packageName + ".ManagerService");
            intent.setPackage(packageName);
            startService(intent);
        }
    }

    private void stopService() {
        if (isServiceRunning(this, getPackageName())) {
            String packageName = getPackageName();
            Intent intent = new Intent(packageName + ".ManagerService");
            intent.setPackage(packageName);
            stopService(intent);
        }
    }

    private void bindService() {
        if (isServiceRunning(this, getPackageName())) {
            String packageName = getPackageName();
            Intent bindIntent = new Intent(packageName + ".ManagerService");
            bindIntent.setPackage(packageName);
            bindService(bindIntent, connection, BIND_AUTO_CREATE);
        }
    }

    private void unbindService() {
        if (isServiceRunning(this, getPackageName()) && mBound) {
            String packageName = getPackageName();
            Intent intent = new Intent(packageName + ".ManagerService");
            intent.setPackage(packageName);
            unbindService(connection);
            mBound = false;
        }
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param context
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(100);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        String name;
        for (int i = 0; i < serviceList.size(); i++) {
            name = serviceList.get(i).service.getClassName();
            if (serviceList.get(i).service.getClassName().contains(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }
}
